﻿using DailyPoetryM.Models;
using System;
using System.Linq.Expressions;
using System.Reflection.Metadata.Ecma335;
using System.Text.Json;

namespace DailyPoetryM.Services;
public class TodayPoetryService : ITodayPoetryService
{
    private readonly IAlertService _alertService;
    private readonly IPoetryStorage _poetryStorage;

    public TodayPoetryService(IAlertService alertService, IPoetryStorage poetryStorage)
    {
        this._alertService = alertService;
        this._poetryStorage = poetryStorage;
    }
    public async Task<TodayPoetry> GetTodayPoetryAsync()
    {
        var token = await GetTokenAsync();
        if (string.IsNullOrWhiteSpace(token))
        {//没有拿到 Token ,此时我们就从本地取一个诗词
            return await GetRandomPoetryAsync();
        }
        //Http的Headers头中指定token
        using var httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Add("X-User-Token", token);
        HttpResponseMessage response;
        try
        {
            response = await httpClient.GetAsync(
                "https://v2.jinrishici.com/sentence");
            response.EnsureSuccessStatusCode();
        }
        catch (Exception e)
        {
            _alertService.Alert("出错了", e.Message, "好的");
            return await GetRandomPoetryAsync();
        }
        //接口结果json转成类对象
        var json = await response.Content.ReadAsStringAsync();
        JinrishiciSentence jinrishiciSentence;
        try
        {
            jinrishiciSentence = JsonSerializer.Deserialize<JinrishiciSentence>(json,
            new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true//转换的时候不区分大小写
            }) ?? throw new JsonException(); //转换为null就抛异常
        }
        catch (Exception e)
        {
            _alertService.Alert("出错了", e.Message, "好的");
            return await GetRandomPoetryAsync();
        }

        try
        {
            return new TodayPoetry
            {
                Snippet = jinrishiciSentence.Data?.Content ?? throw new JsonException(),
                Name = jinrishiciSentence.Data.Origin?.Title ?? throw new JsonException(),
                Dynasty = jinrishiciSentence.Data.Origin?.Dynasty ?? throw new JsonException(),
                Author = jinrishiciSentence.Data.Origin?.Author ?? throw new JsonException(),
                Content = string.Join("\n",
                                jinrishiciSentence.Data.Origin?.Content ?? throw new JsonException()),
                Source = TodayPoetrySources.Jinrishici
            };
        }catch(Exception e)
        {
            _alertService.Alert("出错了", e.Message, "好的");
            return await GetRandomPoetryAsync();
        }
    }
    /// <summary>
    /// 获取Tocken
    /// </summary>
    /// <returns></returns>
    public async Task<String> GetTokenAsync()
    {
        using var httpClient = new HttpClient();
        HttpResponseMessage response;
        try
        {
            response = await httpClient.GetAsync("https://v2.jinrishici.com/token");
            response.EnsureSuccessStatusCode();
        }
        catch (Exception e)
        {
            _alertService.Alert("出错了", e.Message, "好的");
            return string.Empty;
        }
        var json = await response.Content.ReadAsStringAsync();
        try
        {
            var token = JsonSerializer.Deserialize<Token>(json);
            return token.data;
        }
        catch (Exception e)
        {
            _alertService.Alert("出错了", e.Message, "好的");
            return string.Empty;
        }
    }
    /// <summary>
    /// 从本地随机取一个诗词
    /// </summary>
    /// <returns></returns>
    public async Task<TodayPoetry> GetRandomPoetryAsync()
    {
        var Where = Expression.Lambda<Func<Poetry, bool>>(
           Expression.Constant(true),
           Expression.Parameter(typeof(Poetry), "p")
           );
        var poetries = await _poetryStorage.GetPoetriesAsync(
            where:Where,
            skip: new Random().Next(30),//随机数 0~29
            take: 1);
        var poetry = poetries.First();
        return new TodayPoetry
        {
            Snippet = poetry.Snippet,
            Name = poetry.Name,
            Dynasty = poetry.Dynasty,
            Author = poetry.Author,
            Content = poetry.Content,
            Source = TodayPoetrySources.Local
        };
    }
}

public class Token
{
    public string status { get; set; }
    public string data { get; set; }
}
public class JinrishiciOrigin
{
    public string? Title { get; set; } = string.Empty;
    public string? Dynasty { get; set; } = string.Empty;
    public string? Author { get; set; } = string.Empty;
    public List<string>? Content { get; set; } = new();
    public List<string>? Translate { get; set; } = new();
}

public class JinrishiciData
{
    public string? Content { get; set; } = string.Empty;
    public JinrishiciOrigin? Origin { get; set; } = new();
}
public class JinrishiciSentence
{
    public JinrishiciData? Data { get; set; } = new();
}